package LeetCode.leetcode;

/**
 * 最长回文子串
 * @author: leiwenkang02@meituan.com
 * @date: 2018/9/6
 * @time: 19:29
 */
public class Test05最长回文子串 {
    public static void main(String[] args) {
        System.out.println(longestPalindrome("aaaa"));
    }
    public static String longestPalindrome(String s) {
        if (s == null || s.length() == 0) {
            return s;
        }
        int n = s.length();
        String res = null;
        boolean[][] dp = new boolean[n][n];

        for (int i = n - 1; i >= 0; i--) {//i需要逆向遍历，j需要正向遍历，因为必须优先已经拿到dp[i + 1][j - 1]的值
            for (int j = i; j < n; j++) {
                dp[i][j] = s.charAt(i) == s.charAt(j) && (j - i < 3 || dp[i + 1][j - 1]);
                if (dp[i][j] && (res == null || j - i + 1 > res.length())) {
                    res = s.substring(i, j+1);
                }
            }
        }
        return res;
    }
}
